using System.Net;
using System.Net.Sockets;
using Accona.Remoting.Remoting;

namespace Accona.Remoting.Multicast
{
    public class MulticastSender : ISender
    {
        private readonly Socket s;

        public MulticastSender(string mcastGroup, int port, int ttl)
        {
            IPAddress ip = IPAddress.Parse(mcastGroup);

            s = new Socket(AddressFamily.InterNetwork,
                           SocketType.Dgram, ProtocolType.Udp);

            var ipep = new IPEndPoint(IPAddress.Parse(mcastGroup), port);

            s.Connect(ipep);

            s.SetSocketOption(SocketOptionLevel.IP,
                              SocketOptionName.AddMembership, new MulticastOption(ip));

            s.SetSocketOption(SocketOptionLevel.IP,
                              SocketOptionName.MulticastTimeToLive, ttl);
        }

        #region ISender Members

        public void Send(byte[] data)
        {
            s.Send(data);
        }

        #endregion
    }
}